<?php
declare (strict_types=1);

namespace app\api\service\passport;

use think\facade\Cache;
use app\common\model\Setting as SettingModel;
use app\common\enum\Setting as SettingEnum;
use Overtrue\EasySms\EasySms;

/**
 * 服务类：发送短信验证码
 * Class SmsCaptcha
 * @package app\api\service\passport
 */
class SmsCaptcha
{
    // 最大发送次数，默认10次
    protected int $sendTimes = 10;

    // 发送限制间隔时间，默认24小时
    protected int $safeTime = 86400;

    protected string $gateway = 'aliyun';
    protected string $template = '';
    protected $easySms;

    public function __construct()
    {
        $this->initialize();
    }
    public function initialize(){
        $setting = SettingModel::getItem(SettingEnum::SMS);
        $this->gateway = $setting['default'];
        $this->template = $setting['scene']['captcha']['templateCode'];
        $config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,
        
            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
        
                // 默认可用的发送网关
                'gateways' => [
                    $setting['default']
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [],
                'aliyun' => [
                    'access_key_id' => $setting['engine']['aliyun']['AccessKeyId'],
                    'access_key_secret' => $setting['engine']['aliyun']['AccessKeySecret'],
                    'sign_name' => $setting['engine']['aliyun']['sign'],
                ],
                'qcloud' => [
                    'sdk_app_id' => $setting['engine']['qcloud']['SdkAppID'], // 短信应用的 SDK APP ID
                    'secret_id' => $setting['engine']['qcloud']['AccessKeyId'], // SECRET ID
                    'secret_key' => $setting['engine']['qcloud']['AccessKeySecret'], // SECRET KEY
                    'sign_name' => $setting['engine']['qcloud']['sign'], // 短信签名
                ],
                'qiniu' => [
                    'secret_key' => $setting['engine']['qiniu']['AccessKey'],
                    'access_key' => $setting['engine']['qiniu']['SecretKey'],
                ],
            ],
        ];
        
        $this->easySms = new EasySms($config);
        
        
    }
    /**
     * 执行发送短信
     * @param string $mobile
     * @return bool
     */
    public function sendCaptcha(string $mobile): bool
    {
        // 缓存发送记录并判断次数
        $this->record($mobile);
        // 生成验证码
        $smsCaptcha = mt_rand(1000,9999);
        session('smsCaptcha', $smsCaptcha);
        // 发送短信
        $this->easySms->send($mobile, [
            'template' => $this->template,
            'data' => $this->getSmsTemplateData([
                'code' => $smsCaptcha
            ]),
        ]);
        return true;
    }

    /**
     * 记录短信验证码发送记录并判断是否超出发送限制
     * @param string $mobile
     * @return bool
     */
    private function record(string $mobile): bool
    {
        // 获取发送记录缓存
        $record = Cache::get("sendCaptchaSMS.$mobile");
        // 写入缓存:记录剩余发送次数
        if (empty($record)) {
            Cache::set("sendCaptchaSMS.$mobile", ($this->sendTimes - 1), $this->safeTime);
            return true;
        }
        // 判断发送次数是否合法
        if ($record <= 0) {
            throwError('很抱歉，已超出今日最大发送次数限制');
            return false;
        }
        // 发送次数递减
        Cache::dec("sendCaptchaSMS.$mobile");
        return true;
    }

    private function getSmsTemplateData(array $templateParams): array
    {
        if ($this->gateway === 'qcloud') {
            $templateParams = array_values($templateParams);
        }
        return $templateParams;
    }
}